package com.example.qxfw.yjqx.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.qxfw.ybzz.mapper.BaseProductMapper;
import com.example.qxfw.yjqx.service.CshxService;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.xmlbeans.XmlCursor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import static com.example.qxfw.common.util.DocxUtil.*;
import static com.example.qxfw.common.util.DocxUtil.setCellLocation;

@Service
public class CshxServiceImpl implements CshxService {

    @Value("${dmgis.ip}")
    private String dmgisIp;

    @Value("${dmgis.port}")
    private String dmgisPort;

    @Value("${filePath.resourcePath}")
    private String resourcePath;

    @Autowired
    private BaseProductMapper baseProductMapper;


    @Qualifier("mongoSecondTemplate")
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public Object createProduct(String date, String userName, MultipartFile images[]) throws ParseException {
//        ApplicationHome applicationHome = new ApplicationHome(FileUtil.class);
//        String templatePath = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath() +
//                "\\src\\main\\resources\\Documents\\城市火险等级预报模板\\城市火险等级预报模板.docx";
//        String targetPath = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath() +
//                "\\src\\main\\resources\\temp\\城市火险等级预报.docx";
        //模板路径
        String templatePath = resourcePath+"\\Documents\\城市火险等级预报模板\\城市火险等级预报模板.docx";
        //产品路径
        String targetPath = resourcePath+"\\temp\\城市火险等级预报.docx";

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy年MM月dd日");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月dd日HH时");

        Date ybData = sdf.parse(date);
        String ybTimeStr = sdf1.format(ybData);
        String nowTimeStr = sdf2.format(new Date());

        //生成文档
        try (
                InputStream templateInputStream = new FileInputStream(templatePath);
                OutputStream targetOutputStream = new FileOutputStream(targetPath);
                XWPFDocument document = new XWPFDocument(templateInputStream);
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ) {
            List<XWPFParagraph> paragraphs = document.getParagraphs();
            //段落替换
            String[] placeholders = new String[]{"[0]", "[1]", "[2]"};
            //替换内容
            String[] replacements = new String[]{userName, ybTimeStr, nowTimeStr};

            for (int i = 0; i < paragraphs.size(); i++) {
                XWPFParagraph paragraph = paragraphs.get(i);
                String text = paragraph.getText();

                replaceTextInParagraph(paragraph, placeholders, replacements);

                //插入图片
                if (StringUtils.isNotBlank(text) && text.contains("[图片]")) {
                    //获取下标
                    XmlCursor cursor = paragraph.getCTP().newCursor();
                    XWPFParagraph newPara = document.insertNewParagraph(cursor);
                    newPara.setAlignment(ParagraphAlignment.CENTER);//居中
                    XWPFRun newParaRun = newPara.createRun();
                    for (MultipartFile image : images) {
                        //插入图片
                        newParaRun.addPicture(image.getInputStream(), XWPFDocument.PICTURE_TYPE_PNG, "image.png,", Units.toEMU(450), Units.toEMU(406));
                    }
                    document.removeBodyElement(document.getPosOfParagraph(paragraph));
                }

                //插入等级预报数据表格
                if (StringUtils.isNotBlank(text) && text.contains("【城市火险等级预报】")) {

                    //获取下标
                    XmlCursor cursor = paragraph.getCTP().newCursor();
//                    cursor.toNext
                    XWPFTable table = document.insertNewTbl(cursor);
                    //添加表头
                    XWPFTableRow row_0 = table.getRow(0);
                    row_0.getCell(0).setText("站点名称");
                    row_0.addNewTableCell().setText("湿度分量");
                    row_0.addNewTableCell().setText("无降水日分量");
                    row_0.addNewTableCell().setText("温度分量");
                    row_0.addNewTableCell().setText("风力分量");
                    row_0.addNewTableCell().setText("降水分量");
                    row_0.addNewTableCell().setText("火险指数");
                    row_0.addNewTableCell().setText("火险等级");
                    //插入图层表格数据
                    XWPFTableRow dataRow = table.createRow();
                    dataRow.getCell(0).setText("");
                    dataRow.getCell(1).setText("");
                    dataRow.getCell(2).setText("");
                    dataRow.getCell(3).setText("");
                    dataRow.getCell(4).setText("");
                    dataRow.getCell(5).setText("");
                    dataRow.getCell(6).setText("");
                    dataRow.getCell(7).setText("");
                    setTableLocation(table, "center");
                    setCellLocation(table, "CENTER", "center");

                }
                //插入重要地点数据表格
                if (StringUtils.isNotBlank(text) && text.contains("【重要地点火险等级预报】")) {
                    //获取下标
                    XmlCursor cursor = paragraph.getCTP().newCursor();
                    XWPFTable table = document.insertNewTbl(cursor);
                    //添加表头
                    XWPFTableRow row_0 = table.getRow(0);
                    row_0.getCell(0).setText("重要地点");
                    row_0.addNewTableCell().setText("火险等级");
                    row_0.addNewTableCell().setText("联系电话");
                    row_0.addNewTableCell().setText("附近地点");
                    //插入图层表格数据
                    XWPFTableRow dataRow = table.createRow();
                    dataRow.getCell(0).setText("");
                    dataRow.getCell(1).setText("");
                    dataRow.getCell(2).setText("");
                    dataRow.getCell(3).setText("");
                    setTableLocation(table, "center");
                    setCellLocation(table, "CENTER", "center");
                    document.removeBodyElement(document.getPosOfParagraph(paragraph));

                }
            }
            // 将生成的文档保存到输出文件
            document.write(targetOutputStream);

            //获取文档名称

//            String productName = ybTime+city+"城市内涝预警文档.docx";
//            //插入城市内涝预报表数据
//            waterLoggingFcst.setMaker(userName);
//            waterLoggingFcst.setMaketime(new Timestamp(new Date().getTime()));
//            waterLoggingFcst.setDocpath(productName);
//            waterLoggingFcst.setForecasttime(Timestamp.valueOf(sdf2.format(date1)+" "+timeChar+":00:00"));
//            waterLoggingFcst.setRaintype(sXType);
//            waterLoggingFcstMapper.insert(waterLoggingFcst);
//            //保存基本产品表数据
//            BaseProduct baseProduct = new BaseProduct();
//            baseProduct.setProductname(productName);
//            baseProduct.setProducttype(yjType+sXType);
//            baseProduct.setForecasttime(date1);
//            baseProduct.setMaketime(new Date());
//            baseProduct.setBindid(waterLoggingFcst.getId());
//            baseProduct.setMaker(userName);
//            baseProductMapper.insert(baseProduct);
            byte[] buffer = new byte[1024];
            int bytesRead;
            FileInputStream inputStream = new FileInputStream(targetPath);
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, bytesRead);
            }
            byte[] byteArray = byteArrayOutputStream.toByteArray();
//            //保存到mongodb库中
//            HyDocFile hyDocFile = new HyDocFile();
//            hyDocFile.setData(byteArray);
//            hyDocFile.setTable_name("base_product");
//            hyDocFile.setId(String.valueOf(baseProduct.getId()));
//            mongoTemplate.save(hyDocFile);
            // 设置前端响应
            HttpHeaders headers = new HttpHeaders();
            String fileName = "城市内涝等级预报文档.docx";
            headers.setContentDispositionFormData("attachment", new String(fileName.getBytes("UTF-8"), "ISO-8859-1"));
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentLength(byteArray.length);
//            wordToPdf(targetPath,targetPdfPath);
            return new ResponseEntity<>(byteArray, headers, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("文档生成失败");
        }
        return null;
    }

}
